/**
 * 课程11 聚类图
 *
 */

mapboxgl.accessToken = 'pk.eyJ1IjoiNGgzajgiLCJhIjoiY202cTRneXdpMDlheDJpb21rdGs2M3V6cSJ9.Ifg4pD0p8LxYmxmxwoTBNA';

const map = (window.map = new mapboxgl.Map({
  container: 'map',
  center: [121.74380266722233, 31.097567372835357],
  zoom: 5,
  style: 'mapbox://styles/mapbox/standard',
  minZoom: 5,
  maxZoom: 21
}));


// 聚类图
const clusterLayer = () => {
  let points = [
    [121.48211102197638, 31.22894997464809],
    [121.48343561046238, 31.227123120578284],
    [121.48211102197638, 31.22894997464809],
    [121.48343561046238, 31.227123120578284],
    [121.48211102197638, 31.22894997464809],
    [121.48343561046238, 31.227123120578284],
    [121.48211102197638, 31.22894997464809],
    [121.48343561046238, 31.227123120578284],
    [121.48211102197638, 31.22894997464809],
    [121.48343561046238, 31.227123120578284],
    [121.48211102197638, 31.22894997464809],
    [121.48343561046238, 31.227123120578284],
    [121.48211102197638, 31.22894997464809],
    [121.48343561046238, 31.227123120578284],
    [121.48211102197638, 31.22894997464809],
    [121.48343561046238, 31.227123120578284],
    [121.48211102197638, 31.22894997464809],
    [121.48343561046238, 31.227123120578284],
    [121.48211102197638, 31.22894997464809],
    [121.48343561046238, 31.227123120578284],
    [122.83889038980374, 30.754150463006212],
    [122.7245098716179, 30.693334060006123],
  ]



// 2 基础点位数据
  var pointDataGeojson2 = {
    'type': 'FeatureCollection',
    'features': [
      {
        // feature for Mapbox DC
        'type': 'Feature',
        'geometry': {
          'type': 'Point',
          'coordinates': [
            121.48211102197638, 31.22894997464809
          ]
        },
        'properties': {
          'title': 'Mapbox DC',
        }
      },
    ]
  }
  for (let i = 0; i < points.length; i++) {
    let fea = {
      'type': 'Feature',
      'geometry': {
        'type': 'Point',
        'coordinates': points[i]
      },
      'properties': {
        mag: 4,
        'title': 'Mapbox DC',
        icon: 'custom-marker',
        diffTag: '聚类点'
      }
    }
    pointDataGeojson2.features.push(fea)
  }

  var pointSource2 = {
    type: 'geojson',
    data: {
      type: "FeatureCollection",
      features: []
    },
  }
// 3 创建数据源并添加
  var pointSource = {
    type: 'geojson',
    data: {
      type: "FeatureCollection",
      features: []
    },
    cluster: true,
    clusterMaxZoom: 14, // Max zoom to cluster points on
    clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
  }
  map.addSource('pointSource', pointSource)
  map.addSource('pointSource2', pointSource2)

  var point_source = map.getSource('pointSource');
  var point_source2 = map.getSource('pointSource2');
  point_source.setData(pointDataGeojson2)
  point_source2.setData(pointDataGeojson2)


// 4 创建图层并添加
  var cluster = {
    id: 'clusterLayer',
    type: 'circle',
    filter: ['has', 'point_count'],
    source: 'pointSource',
    layout: {
      visibility: 'visible',
      "icon-allow-overlap": true,
      "icon-ignore-placement": false,
    },
    'paint': {
      // Use step expressions (https://docs.mapbox.com/style-spec/reference/expressions/#step)
      // with three steps to implement three types of circles:
      //   * Blue, 20px circles when point count is less than 100
      //   * Yellow, 30px circles when point count is between 100 and 750
      //   * Pink, 40px circles when point count is greater than or equal to 750

      // 插值表达式-文档地址
      //  https://docs.mapbox.com/style-spec/reference/expressions/#interpolate
      'circle-color': [
        'step',
        ['get', 'point_count'],
        '#5db3ac',
        10, '#f1f075',
        750, '#f28cb1'
      ],
      'circle-radius': [
        'step',
        ['get', 'point_count'],
        1,
        2, 50,
        5, 80
      ],
      'circle-emissive-strength': 10 , // Controls the intensity of light emitted on the source features
    },
  }
  map.addLayer(cluster)
}


const laybelLayer = () => {
  map.addLayer({
    id: 'cluster-count',
    type: 'symbol',
    source: 'pointSource',
    // filter: ['has', 'point_count'],
    layout: {
      'text-field': ['get', 'point_count_abbreviated'],
      'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
      'text-size': 12,
    }
  });
}

const pointLayer = () => {
  map.loadImage(
    'https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png', (error, image) => {
      if (error) throw error;
      map.addImage('custom-marker', image);
    })
  map.addLayer({
    id: 'cluster-point',
    type: 'symbol',
    source: 'pointSource',
    layout: {
      "icon-image": ['get', 'icon'],
      "icon-size": 1,
      "icon-allow-overlap": true,
      "icon-ignore-placement": false,
    },
  });
}

const main = () => {
  // 聚类图层
  clusterLayer()

  // 聚类文字图层
  laybelLayer()

  // 点位图层
  pointLayer()
}


map.on('click', (ev) => {
  console.log(ev)
  const features = map.queryRenderedFeatures(ev.point, {
    layers: ['clusterLayer', 'cluster-point']
  });
  console.log({
    features
  })
  // 注意区分点击的是聚类图点位 还是 点位图层点位
  if (features.length == 1) {
    if (features[0].properties.diffTag == '聚类点') {
      console.log('点击了聚类点');
      return;
    }
  }
  const clusterId = features[0].properties.cluster_id;

  // 根据当前点击的聚类圆 feature cluster_id 查询当前聚类圈的所有数据
  map.getSource('pointSource').getClusterChildren(clusterId, (err, features) => {
    console.log({
      点击的聚类数据: features
    })
  })

  // 根据当前点击的聚类圆 feature 做出平滑移动层级
  map.getSource('pointSource').getClusterExpansionZoom(
    clusterId,
    (err, zoom) => {
      if (err) return;
      map.easeTo({
        center: features[0].geometry.coordinates,
        zoom: zoom
      });
    }
  );


})

map.on('load', () => {
  main()
})
